package com.gocoolmall.ware.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.annotation.PostConstruct;
import java.util.HashMap;

@Configuration
public class MyRabbitConfig {

//    @Autowired
    RabbitTemplate rabbitTemplate;

    @Primary
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory){
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        this.rabbitTemplate = rabbitTemplate;
        rabbitTemplate.setMessageConverter(messageContext());
        initRabbitTemplate();
        return rabbitTemplate;
    }

    //    @PostConstruct //MyRabbitConfig对象创建完成以后，执行这个方法。
    public void initRabbitTemplate(){
        //设置确认回调
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            /**
             *1、只要消息抵达Broker就是ack=ture
             * @param correlationData  当前消息的唯一关联数据（这个是消息的唯一id)
             * @param ack   消息是否成功收到
             * @param cause 失败的原因
             */
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                /**
                 * TODO
                 * 1、做好消息的确认机制（pulisher.consumer【手动akc】）
                 * 2、每一个发送的消息都在数据库做好记录。定期将失败的消息再次发送。
                 */
                System.out.println("confir..correlationDate["+correlationData+"]==>ack["+ack+"]cause【"+cause+"】");
            }
        });
        //设置确认回调
        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            /**
             * 只要消息没有投递给指定的队列，就触发这个失败回调
             * @param message      投递失败的消息详细信息
             * @param replyCode    回复的状态码
             * @param replyText    回复的文本内容
             * @param exchange     当时这个消息发给哪个交换机
             * @param routingKey   当时这个消息用户哪个路由键
             */
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
                System.out.println("Fail Message["+message+"]===>replyCode["
                        + replyCode+"]===>exchange["+exchange+"]===>routingKey["+routingKey+"]");
            }
        });
    }
    /**
     * 使用JSON序列化机制，进行消息转换。
     *
     * @return
     */
    @Bean
    public MessageConverter messageContext() {
        return new Jackson2JsonMessageConverter();
    }

    //创建一个交换机
    @Bean
    public Exchange stockEventExchange() {
        //String name, boolean durable, boolean autoDelete, Map<String, Object> arguments
        Exchange topicExchange = new TopicExchange("stock-event-exchange", true, false);
        return topicExchange;
    }

    //创建于一个消息队列
    @Bean
    public Queue stockReleaseStockQueue() {
        //String name, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments
        return new Queue("stock.release.stock.queue", true, false, false);
    }

    //创建于延迟队列
    @Bean
    public Queue stockDelayQueue() {
        HashMap<String, Object> arguments = new HashMap<>();
        /**
         * x-dead-letter-exchange: order-event-exchange
         * x-dead-letter-routing-key: order.release.order  //路由件
         * x-message-ttl: 60000  //消息过期时间
         */
        arguments.put("x-dead-letter-exchange", "stock-event-exchange");
        arguments.put("x-dead-letter-routing-key", "stock.release");
        arguments.put("x-message-ttl", 120000); //2分钟
        //String name, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments
        return new Queue("stock.delay.queue", true, false, false, arguments);
    }

    //创建一个绑定普通队列关系
    @Bean
    public Binding stockReleaseBinding() {
        //String destination,
        // Binding.DestinationType destinationType,
        // String exchange,
        // String routingKey,
        // Map<String, Object> arguments
        return new Binding("stock.release.stock.queue",
                Binding.DestinationType.QUEUE,
                "stock-event-exchange",
                "stock.release.#", null);

    }

    //创建一个绑定延迟队列
    @Bean
    public Binding stockLockedBinding() {
        //String destination,
        // Binding.DestinationType destinationType,
        // String exchange,
        // String routingKey,
        // Map<String, Object> arguments
        return new Binding("stock.delay.queue",
                Binding.DestinationType.QUEUE,
                "stock-event-exchange",
                "stock.locked", null);
    }

    //创建一个监听
//    @RabbitListener(queues = "stock.release.stock.queue")
//    public void handle(Message message){
//
//    }
}